const util = require('../../../../util/util.js')

let playTimeInterval
let recordTimeInterval
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
const rangeList = {
  8000:'16000 ~ 48000',
  11025:'16000 ~ 48000',
  12000:'24000 ~ 64000',
  16000:'24000 ~ 96000',
  22050:'32000 ~ 128000',
  24000:'32000 ~ 128000',
  32000:'48000 ~ 192000',
  44100:'64000 ~ 320000',
  48000:'64000 ~ 320000'
}
Page({
  data: {
    title:'录音',
    pageTitle:'',
    theme: 'light',
    recording: false, // 录音中
    playing: false, // 播放中
    hasRecord: false, // 已经录音
    recordTime: 0, // 录音时长
    playTime: 0, // 播放时长
    formatedRecordTime: '00:00:00', // 录音时间
    formatedPlayTime: '00:00:00', // 播放时间
    schema:[
      {
        label:'录音时长',
        prop:'duration',
        type:'number'
      },
      {
        label:'采样率',
        prop:'sampleRate',
        type:'picker',
        labelOptions:['8000','11025','12000','16000','22050','24000','32000','44100','48000'],
        valueOptions:[8000,11025,12000,16000,22050,24000,32000,44100,48000],
      },
      {
        label:'录音通道数',
        prop:'numberOfChannels',
        type:'picker',
        labelOptions:['1','2'],
        valueOptions:[1,2],
      },
      {
        label:'编码码率',
        prop:'encodeBitRate',
        type:'number'
      },
      {
        label:'码率范围',
        prop:'range',
        type:'text',
      },
      {
        label:'音频格式',
        prop:'format',
        type:'picker',
        labelOptions:['mp3','aac','wav','PCM'],
        valueOptions:['mp3','aac','wav','PCM']
      },
      {
        label:'指定帧大小',
        prop:'frameSize',
        type:'number'
      }
    ],
    options:{
      duration:10000,
      sampleRate:44100,
      numberOfChannels:1,
      encodeBitRate:192000,
      range:'64000 ~ 320000',
      format:'mp3',
      frameSize:50
    },
    result:{},
    apiName:'',
    isPause:false
  },

  onHide() {
    if (this.data.playing) {
      this.stopVoice()
    } else if (this.data.recording) {
      this.stopRecordUnexpectedly()
    }
  },

  onLoad(options) {
    console.log(options)
    if(options&&options.zh){
      this.setData({
        zh: options.zh,
        remark:options.remark,
        weburl:options.weburl
      })
    }

    if (wx.onThemeChange) {
      wx.onThemeChange(({theme}) => {
        this.setData({theme})
      })
    }
    const that = this
    // 监听录音开始事件
    recorderManager.onStart((res) => {
      console.log('recorderManage: onStart')
      // 录音时长记录 每秒刷新
      recordTimeInterval = setInterval(() => {
        that.data.recordTime += 1
        const recordTime = that.data.recordTime
        that.setData({
          formatedRecordTime: util.formatTime(that.data.recordTime),
          recordTime
        })
      }, 1000)
    })

    // 监听录音停止事件
    recorderManager.onStop((res) => {
      console.log('recorderManage: onStop')
      that.setData({
        hasRecord: true, // 录音完毕
        recording: false,
        tempFilePath: res.tempFilePath,
        formatedPlayTime: util.formatTime(that.data.playTime),
      })
      this.setData({
        result:res,
        apiName:'RecorderManager.onStop'
      })
      // 清除录音计时器
      clearInterval(recordTimeInterval)
    })
    //监听录音异常事件
    recorderManager.onError((err)=>{
      this.setData({
        result:err,
        apiName:'RecorderManager.onError'
      })
    })
    //监听录音暂停
    recorderManager.onPause(()=>{
      console.log('recorderManage: onPause')
      // 清除录音计时器
      clearInterval(recordTimeInterval)
    })
    //监听录音继续
    recorderManager.onResume(()=>{
      console.log('recorderManage: onResume')
      recordTimeInterval = setInterval(() => {
        that.data.recordTime += 1
        const recordTime = that.data.recordTime
        that.setData({
          formatedRecordTime: util.formatTime(that.data.recordTime),
          recordTime
        })
      }, 1000)
    })
    //监听录音中断
    recorderManager.onInterruptionBegin(()=>{
      console.log('recorderManage: onInterruptionBegin')
    })
    recorderManager.onInterruptionEnd(()=>{
      console.log('recorderManage: onInterruptionEnd')
    })
    recorderManager.onFrameRecorded((res)=>{
      this.setData({
        result:res,
        apiName:'RecorderManager.onFrameRecorded'
      })
    })
    // 监听播放开始事件
    innerAudioContext.onPlay(() => {
      console.log('innerAudioContext: onPlay')
      playTimeInterval = setInterval(() => {
        const playTime = that.data.playTime + 1
        if (that.data.playTime === that.data.recordTime) {
          that.stopVoice()
        } else {
          console.log('update playTime', playTime)
          that.setData({
            formatedPlayTime: util.formatTime(playTime),
            playTime
          })
        }
      }, 1000)
    })

    innerAudioContext.onStop(() => {

    })
  },

  setOptons(e) {
    console.log(e.detail)
    this.setData({
      options:e.detail.formData
    })
    if (e.detail.prop === 'sampleRate') {
      this.setData({
        'options.range':rangeList[this.data.options.sampleRate],
        'options.encodeBitRate':''
      })
    }
  },

  startRecord() {
    this.setData({
      recording: true // 录音开始
    })
    console.log('00',JSON.stringify(recorderManager))
    recorderManager.start(this.data.options) // 开始录音
  },

  pauseRecord(){
    recorderManager.pause()
    this.setData({
      isPause:true
    })
  },
  resumeRecord(){
    recorderManager.resume()
    this.setData({
      isPause:false
    })
  },

  stopRecord() {
    recorderManager.stop() // 停止录音
  },

  stopRecordUnexpectedly() {
    const that = this
    wx.stopRecord({
      success() {
        console.log('stop record success')
        clearInterval(recordTimeInterval)
        that.setData({
          recording: false,
          hasRecord: false,
          recordTime: 0,
          formatedRecordTime: util.formatTime(0)
        })
      },
      fail(err){
        this.setData({
          result:{
            ...this.data.result,
            'stopRecord':'wx.stopRecord error',
            ...err
          }
        })
      }
    })
  },

  playVoice() {
    innerAudioContext.src = this.data.tempFilePath
    this.setData({
      playing: true,
    }, () => {
      innerAudioContext.play()
    })
  },

  pauseVoice() {
    clearInterval(playTimeInterval)
    innerAudioContext.pause()
    this.setData({
      playing: false
    })
  },

  stopVoice() {
    clearInterval(playTimeInterval)
    innerAudioContext.stop()
    this.setData({
      playing: false,
      formatedPlayTime: util.formatTime(0),
      playTime: 0
    })
  },

  clear() {
    clearInterval(playTimeInterval)
    innerAudioContext.stop()
    this.setData({
      playing: false,
      hasRecord: false,
      tempFilePath: '',
      formatedRecordTime: util.formatTime(0),
      recordTime: 0,
      playTime: 0
    })
  }
})
